<template>
	<div class="page-my-info">
		<!-- <div class="title">基本信息</div> -->

		<el-form size="small" class="my-form" label-width="100px" :model="form" :disabled="saving">
			<div class="close cursor" @click="$router.go(-1)">
				<i class="el-icon-close"></i>
			</div>
			<div class="avatar">
				<el-form-item class="avatar-v" label>
					<cl-upload v-model="form.headImg"></cl-upload>
				</el-form-item>
			</div>
			<div class="form-item">
				<!-- <el-form-item label="用户名：">
					<div>
						{{ form.username }}
					</div>
				</el-form-item> -->
				<el-form-item label="用户名：">
					<el-input v-model="form.username" maxlength="16" clearable></el-input>
				</el-form-item>

				<el-form-item label="手机号：">
					<!-- <el-input type="password" v-model="form.password"></el-input> -->
					<div class="my-change">
						<div>{{ userInfo.phone || '无' }}</div>
						<div class="_change-btn" @click="infobanding('phone')">
							{{ userInfo.phone ? '修改' : '绑定' }}
						</div>
					</div>
				</el-form-item>
				<el-form-item label="登录密码：">
					<!-- <el-input type="password" v-model="form.password"></el-input> -->
					<div class="my-change">
						<div>**********</div>
						<div class="_change-btn" @click="infobanding('pass')">修改</div>
					</div>
				</el-form-item>
				<el-form-item label="微信：">
					<!-- <el-input type="password" v-model="form.password"></el-input> -->
					<div
						class="my-change"
						@click="!userInfo.bindWechat ? infobanding('wx') : () => {}"
					>
						<div>{{ userInfo.bindWechat ? userInfo.wechatName : '未绑定' }}</div>
						<div v-if="!userInfo.bindWechat" class="_change-btn">
							{{ userInfo.bindWechat ? '已绑定' : '绑定' }}
						</div>
					</div>
				</el-form-item>
				<el-form-item label="团队名称：">
					<el-input
						v-if="userInfo.isTeam"
						v-model="form.departmentName"
						clearable
					></el-input>
					<div v-else>{{ form.departmentName }}</div>
				</el-form-item>

				<el-form-item label>
					<el-button type="primary" @click="save" :disabled="saving">保存修改</el-button>
				</el-form-item>
			</div>
		</el-form>
		<cl-form ref="cl-form">
			<!-- 默认手机号 -->
			<template #slot-default-phone>
				<div class="code">
					<el-input
						placeholder="请输入验证码"
						v-model="userInfo.phone"
						disabled
						clearable
					></el-input>
				</div>
			</template>
			<!-- 扫码 -->
			<template #slot-wxscan>
				<div class="wxscan">
					<el-image
						style="width: 100px; height: 100px"
						:src="wxqrcodeUrl"
						fit="cover"
					></el-image>
				</div>
			</template>
			<!-- 获取验证码 -->
			<template #slot-code="{scope}">
				<div class="code">
					<el-input
						placeholder="请输入验证码"
						maxlength="4"
						v-model="scope.code"
						clearable
					></el-input>
					<div
						class="getcaptach"
						@click.stop="getCaptach"
						:style="{ color: timeout ? '#ccc' : '#1890FF' }"
					>
						{{ timeout ? timeout + 's' : '获取验证码' }}
					</div>
				</div>
			</template>

			<!-- 切换修改密码选项 -->
			<template #slot-editpasstype>
				<div class="swichpass" style="color:#1890FF;text-align:right;cursor: pointer;">
					<span
						class="passchange"
						v-if="editPassWordSwitchVal === 'pass' && userInfo.phone"
						@click="editPassWordSwitchVal = 'phone'"
						>使用手机验证码修改</span
					>
					<span
						class="passchange"
						v-if="editPassWordSwitchVal === 'phone'"
						@click="editPassWordSwitchVal = 'pass'"
						>使用原密码修改</span
					>
				</div>
			</template>
		</cl-form>
		<captcha ref="captcha" @callback="timeoutfunc"></captcha>
	</div>
</template>

<script>
import { mapGetters } from 'vuex';
import captcha from '@/components/captcha.vue';
import qrcode from 'qrcode';
export default {
	data() {
		return {
			form: {},
			saving: false,
			editPassWordSwitchVal: 'pass',
			editPassForm: '',
			editphoneForm: '',
			wxBindForm: '',
			wxqrcodeUrl: '',
			timeout: '',
			isbindphone: false,
			phone: '',
			timers: ''
		};
	},
	components: {
		captcha
	},
	computed: {
		...mapGetters(['userInfo'])
	},
	watch: {
		editPassWordSwitchVal(val) {
			if (val == 'phone') {
				this.editPassForm.close();
				this.undatePhone();
			} else {
				this.editphoneForm.close();
				this.undatePass();
			}
		}
	},

	mounted() {
		this.form = {
			...this.userInfo
		};
	},

	methods: {
		// 根据type 来决定做什么
		infobanding(type) {
			switch (type) {
				case 'wx':
					// 绑定微信
					console.log('wx');
					this.bindWechat();
					break;
				case 'pass':
					// 修改密码
					this.editPassWordSwitchVal = 'pass';
					this.undatePass();
					break;
				case 'phone':
					// 是否有手机号有则修改无则绑定
					if (this.userInfo.phone) {
						this.undatePhone('phone');
					} else {
						this.bindPhone('binding');
					}
					break;
			}
		},
		// 倒计时
		timeoutfunc() {
			this.timeout = 59;
			let timer = setInterval(() => {
				this.timeout--;
				if (this.timeout <= 0) {
					clearInterval(timer);
					this.timeout = '';
				}
			}, 1000);
		},
		// 获取手机号验证码
		getCaptach() {
			if (this.isbindphone) {
				if (this.phone.length == 11) {
					this.$refs['captcha'].open(this.phone);
				} else {
					console.log('手机号输入错误请重新输入');
					this.$message.error('手机号输入错误请重新输入');
				}
			} else {
				this.$refs['captcha'].open(this.userInfo.phone);
			}
		},
		// 验证手机号修改密码 验证手机号修改手机号
		undatePhone(name = 'pass') {
			this.editphoneForm = this.$refs['cl-form'].open({
				props: {
					title: name == 'pass' ? '修改登录密码' : '修改手机号',
					width: '400px',
					showClose: false
				},
				op: {
					confirmButtonText: '下一步',
					cancelButtonText: '取消',

					layout: ['cancel', 'confirm'] // 同crud下的layout
				},

				items: [
					{
						prop: 'phone',
						props: {
							'label-width': '68px',
							label: '手机号',
							clearable: true
						},
						hidden: false,
						component: {
							name: 'slot-default-phone'
						}
					},
					{
						prop: 'code',
						props: {
							'label-width': '68px',
							label: '验证码',
							clearable: true
						},

						component: {
							name: 'slot-code'
						},

						hidden: false,
						rules: {
							required: true,
							message: '验证码不能为空'
						}
					},
					{
						prop: 'select',
						props: {
							'label-width': '68px',
							label: ''
						},
						hidden: name == 'pass' ? false : true,
						component: {
							name: 'slot-editpasstype'
						}
					}
				],

				on: {
					submit: ({ data, done, close }) => {
						console.log('下一步');
						const { code } = data;
						done();
						close();
						this.timeout = '';
						if (name == 'pass') {
							this.$service.common
								.modifyPhone({
									phone: this.userInfo.phone,
									code
								})
								.then(() => {
									this.$refs['cl-form'].open({
										props: {
											title: '修改登录密码',
											width: '400px',
											showClose: false
										},

										items: [
											{
												prop: 'password',
												hidden: false,
												props: {
													'label-width': '68px',
													label: '新密码'
												},

												component: {
													name: 'el-input',
													props: {
														'show-password': true
													},
													attrs: {
														placeholder: '请输入新密码',
														maxlength: 20,
														minlength: 6,
														clearable: true
													}
												},
												rules: [
													{
														required: true,
														message: '新密码不能为空'
													},
													{
														min: 6,
														max: 20,
														message: '密码长度在6-20个字符'
													}
												]
											}
										],

										on: {
											submit: ({ data, done, close }) => {
												const { password } = data;
												this.$service.common
													.modifyPwdByPhone({
														password
													})
													.then(() => {
														this.$message.success('修改成功');
														done();
														close();
													})
													.catch(err => {
														this.$message.error(err);
														done({ keep: true });
													});
											}
										}
									});
								})
								.catch(err => {
									this.$message.error(err);
									done({ keep: true });
								});
						} else {
							this.$service.common
								.checkPhone({
									phone: this.userInfo.phone,
									code
								})
								.then(() => {
									this.bindPhone();
								})
								.catch(err => console.error(err));
						}
					}
				}
			});
		},
		// 修改登入密码
		undatePass() {
			this.editPassForm = this.$refs['cl-form'].open({
				props: {
					title: '修改登录密码',
					width: '400px',
					showClose: false
				},
				op: {
					confirmButtonText: '保存',
					cancelButtonText: '取消',

					layout: ['cancel', 'confirm'] // 同crud下的layout
				},

				items: [
					{
						prop: 'oldPassword',
						props: {
							'label-width': '68px',
							label: '原密码'
						},
						hidden: false,
						component: {
							name: 'el-input',
							props: {
								'show-password': true
							},
							attrs: {
								placeholder: '请输入原密码',
								maxlength: 20,
								minlength: 6,
								clearable: true
							}
						},
						rules: [
							{
								required: true,
								message: '原密码不能为空'
							},
							{
								min: 6,
								max: 20,
								message: '密码长度在6-20个字符'
							}
						]
					},
					{
						prop: 'password',
						hidden: false,
						props: {
							'label-width': '68px',
							label: '新密码'
						},

						component: {
							name: 'el-input',
							props: {
								'show-password': true
							},
							attrs: {
								placeholder: '请输入新密码',
								maxlength: 20,
								minlength: 6,
								clearable: true
							}
						},
						rules: [
							{
								required: true,
								message: '新密码不能为空'
							},
							{
								min: 6,
								max: 20,
								message: '密码长度在6-20个字符'
							}
						]
					},
					{
						prop: 'select',
						props: {
							'label-width': '68px',
							label: ''
						},

						component: {
							name: 'slot-editpasstype'
						}
					}
				],

				on: {
					submit: ({ data, done, close }) => {
						const { oldPassword, password } = data;
						if (oldPassword === password) {
							this.$message.error('新旧密码不能一致');
							done();
							return false;
						}
						let reg = /^[a-zA-Z0-9]/;
						if (!reg.test(password)) {
							this.$message.warning('密码需包含数字或字母且不能以特殊字符开头');
							done();
							return false;
						}
						this.$service.common
							.modifyPwd({ oldPassword, password })
							.then(async () => {
								this.$message.success('修改成功');
								await self.$store.dispatch('userInfo');
								done();
								close();
							})
							.catch(err => {
								this.$message.error(err);
								done({ keep: true });
							});
					}
				}
			});
		},
		// 绑定微信
		bindWechat() {
			this.$service.common
				.bindWechat({
					type: 1,
					source: 0
				})
				.then(async res => {
					console.log(res);
					this.wxqrcodeUrl = await qrcode.toDataURL(res.url, {
						errorCorrectionLevel: 'H',
						type: 'image/jpeg',
						margin: 1
					});
					this.wxBindForm = this.$refs['cl-form'].open({
						props: {
							title: '扫码绑定微信',
							width: '431px',
							showClose: false
						},
						op: {
							layout: []
						},
						items: [
							{
								prop: 'wxscan',
								props: {
									'label-width': '0px'
								},

								component: {
									name: 'slot-wxscan'
								}
							}
						],
						on: {
							close: () => {
								clearInterval(this.timers);
							}
						}
					});
					this.wechatResult(res.ticket);
				})
				.catch(err => this.$message.error(err));
		},
		// 绑定结果 传入 ticket
		wechatResult(ticket) {
			this.timers = setInterval(() => {
				this.$service.common
					.wechatResult({
						ticket
					})
					.then(res => {
						if (res) {
							if (res.status == 1) {
								clearInterval(this.timers);
								this.$message({
									type: 'success',
									message: '绑定成功'
								});
								this.wxBindForm.close();
								this.$store.dispatch('userInfo');
							}
						}
					})
					.catch(err => self.$message.error(err));
			}, 2000);
		},

		// 绑定修改手机号
		bindPhone(type = 'update') {
			this.$refs['cl-form'].reset();
			this.isbindphone = true;
			const self = this;
			this.$refs['cl-form'].open({
				props: {
					title: type == 'update' ? '修改手机号' : '绑定手机号',
					width: '431px',
					showClose: false
				},
				op: {
					confirmButtonText: '保存',
					cancelButtonText: '取消',

					layout: ['cancel', 'confirm'] // 同crud下的layout
				},

				items: [
					{
						prop: 'phone',
						props: {
							'label-width': '80px',
							label: '新手机号',
							clearable: true
						},

						component: {
							name: 'el-input',
							attrs: {
								placeholder: '请输入您的手机号',
								maxlength: 11
							},
							on: {
								change(val) {
									self.phone = val;
								}
							}
						},
						rules: {
							required: true,
							message: '手机号不能为空'
						}
					},
					{
						prop: 'code',
						props: {
							'label-width': '80px',
							label: '验证码',
							clearable: true
						},

						component: {
							name: 'slot-code'
						},
						rules: {
							required: true,
							message: '验证码不能为空'
						}
					}
				],

				on: {
					submit: ({ data, done, close }) => {
						const { phone, code } = data;
						// 修改手机号
						if (type == 'update') {
							this.$service.common
								.modifyPhone({ code, phone })
								.then(async () => {
									this.$message({
										type: 'success',
										message: '修改成功'
									});

									await self.$store.dispatch('userInfo');

									done();
									close();
								})
								.catch(err => {
									this.$message.error(err);
									done({ keep: true });
								});
						} else {
							// 绑定手机号
							this.$service.common
								.bindPhone({ code, phone })
								.then(async () => {
									this.$message({
										type: 'success',
										message: '绑定成功'
									});

									await self.$store.dispatch('userInfo');

									done();
									close();
								})
								.catch(err => {
									this.$message.error(err);
									done({ keep: true });
								});
						}
					}
				}
			});
		},
		save() {
			this.saving = true;

			const { headImg, username, departmentName, departmentId } = this.form;

			this.$service.common
				.userUpdate({
					// ...this.form,
					headImg,
					username,
					departmentId,
					departmentName
					// password
				})
				.then(() => {
					this.form.password = '';
					this.$message.success('修改成功');
					this.$store.dispatch('userInfo');
				})
				.catch(err => {
					this.$message.error(err);
				})
				.done(() => {
					this.saving = false;
				});
		}
	}
};
</script>

<style lang="stylus" scoped>
>>>.el-form-item__content {
	display: flex;
}

>>>.el-dialog .el-dialog__body {
	padding: 20px 61px;
}

>>>.swichpass {
	display: flex;
	width: 100%;
	justify-content: flex-end;
}

.page-my-info {
	background-color: #fff;
	width: 871px;
	height: 428px !important;
	padding: 20px 20px 20px 20px;
	box-sizing: border-box;
	margin: 0 auto;
	margin-top: 68px;
	box-sizing: border-box;
	border-radius 6px

	.el-form {
		// width: 400px;
	}

	.my-form {
		display: flex;
		align-items: center;
		position relative
		.avatar {
			height: 198px;
			display: flex;
			align-items: center;
			justify-content: center;
			border-right: 1px solid rgba(208, 208, 208, 1);
			padding-right: 89px;
			margin-right: 75px;

			.upload-wrap {
				width: 102px;
				height: 102px;
				background: rgba(0, 0, 0, 0);
				border-radius: 50%;
			}
		}

		.my-change {
			display: flex;
			align-items: center;
			width: 100%;
			position: relative;

			._change-btn {
				color: #1890FF;
				font-size: 14px;
				position: absolute;
				right: 0;
				cursor: pointer;
			}
		}

		.form-item {
			padding-top: 72px;
		}
	}

	.title {
		color: #000;
		margin-bottom: 30px;
		font-size: 15px;
	}
}

.code {
	display: flex;
	position: relative;
	width: 100%;

	.getcaptach {
		position: absolute;
		right: 0px;
		color: #1890FF;
		width: 90px;
		font-size: 14px;
		cursor: pointer;
		text-align: center;
	}
}
.wxscan {
	display: flex;
    justify-content: center;
    width: 100%;
}

>>>.el-dialog__footer {
	display: flex;
	justify-content: center;

	.el-button--default {
		margin: 0 30px;
		width: 80px;
		height: 30px;
		color: #C0C4CC;
		border: 1px solid rgba(192, 196, 204, 1);
		border-radius: 17px;
	}

	.el-button--success {
		margin: 0 30px;
		width: 80px;
		height: 30px;
		color: #fff;
		background: rgba(255, 68, 0, 1);
		border-radius: 17px;
		border: solid 0px;
	}
}
.close {
	width 28px
	height 28px
	line-height 28px
	font-size 28px
	position absolute
	right 0px
	top 0px
	cursor pointer

}
</style>
